<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <PageFilter v-model:query="filterInfo.query" :filter-list="filterInfo.list">
      <template v-slot:filter-enabled>
        <el-button :disabled="!canDisabled" @click="enable()">启用</el-button>
      </template>
      <template v-slot:filter-disabled>
        <el-button :disabled="!canEnabled" @click="disable()">停用</el-button>
      </template>
    </PageFilter>
    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="getInvokeSystemConfig"
      v-model:query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :handle="tableInfo.handle"
      :check-box="true"
      :tab-index="true"
      @handleEvent="handleEvent"
    >
      <template v-slot:col-isAsyn="scope">
        <span>{{
          getOptionLabel(scope.row.isAsyn, listTypeInfo.enableList)
        }}</span>
      </template>
      <template v-slot:col-isEnable="scope">
        <span>{{
          getOptionLabel(scope.row.isEnable, listTypeInfo.enableList)
        }}</span>
      </template>
    </TableContainer>
    <!-- 新增修改弹窗 -->
    <PageDialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title[dialogInfo.type]"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <!-- form -->
      <PageForm
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
        :list-type-info="listTypeInfo"
      >
        <template v-slot:form-type>
          <el-input
            v-model="formInfo.data.typeName"
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择接口类型"
          >
            <template #append>
              <el-icon @click="openInterfaceTypePage"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-interfaceId>
          <el-input
            v-model="formInfo.data.interfaceName"
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择接口"
          >
            <template #append>
              <el-icon @click="openSystemList"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </PageForm>
    </PageDialog>
    <SelectInterface
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      v-model:query="selectUserInfo.query"
      :api="selectUserInfo.api"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectUserCallBack"
    />
    <SelectInterfaceType
      v-if="selectInterfaceType.visible"
      v-model:showDialog="selectInterfaceType.visible"
      v-model:query="selectInterfaceType.query"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectInterfaceTypeCallBack"
    />
  </div>
</template>

<script setup name="invokeSystemConfig">
import SelectInterface from './selectInterface'
import SelectInterfaceType from './selectInterfaceType'
import _ from 'lodash'
import {
  getInvokeSystemConfig,
  createInvokeSystemConfig,
  updateInvokeSystemConfig,
  startInvokeSystemConfig,
  stopInvokeSystemConfig,
  deleteInvokeSystemConfig,
  getThirdSystemAll,
  getInvokeInterfaceAll,
} from '@/api/base.js'

const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    searchType: 'orderSequence',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      show: proxy.$permission('invokeSystemConfig:add'),
      event: create,
    },
    {
      type: 'slot',
      label: '启用',
      value: 'enabled',
      show: proxy.$permission('invokeSystemConfig:enable'),
    },
    {
      type: 'slot',
      label: '停用',
      value: 'disabled',
      show: proxy.$permission('invokeSystemConfig:disable'),
    },
    {
      type: 'input',
      label: '接口类型',
      value: 'typeLike',
      event: search,
    },
    // {
    //   type: "input",
    //   label: "接口类型描述",
    //   value: "typeNameLike",
    //   event: search
    // },
    {
      type: 'input',
      label: '接口名称',
      value: 'interfaceNameLike',
      event: search,
    },
    {
      type: 'select-model',
      label: '是否启用',
      value: 'isEnable',
      code: 'yes_or_no',
      event: search,
    },
    {
      type: 'select-model',
      label: '是否异步',
      value: 'isAsyn',
      code: 'yes_or_no',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  selections: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [
    { label: '接口类型', value: 'type' },
    { label: '接口类型描述', value: 'typeName' },
    { label: '客户端ID', value: 'clientId' },
    { label: '客户端名称', value: 'clientName' },
    { label: '接口名称', value: 'interfaceName' },
    { label: '是否异步', type: 'slot', value: 'isAsyn' },
    { label: '是否启用', type: 'slot', value: 'isEnable' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '启用',
        event: enable,
        show: proxy.$permission('invokeSystemConfig:enable'),
        ifRender: function (row) {
          return row.isEnable === 0
        },
      },
      {
        label: '停用',
        event: disable,
        show: proxy.$permission('invokeSystemConfig:disable'),
        ifRender: function (row) {
          return row.isEnable === 1
        },
      },
      {
        label: '修改',
        event: showUpdate,
        show: proxy.$permission('invokeSystemConfig:update'),
        ifRender: function (row) {
          return row.isEnable === 0
        },
      },
      {
        label: '删除',
        event: del,
        show: proxy.$permission('invokeSystemConfig:del'),
        ifRender: function (row) {
          return row.isEnable === 0
        },
      },
    ],
  },
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: { isAsyn: 0 },
  fieldList: [
    {
      label: '接口类型',
      value: 'type',
      type: 'slot',
      required: true,
      code: 'interface_invoke_type',
    },
    {
      label: '接口名称',
      value: 'interfaceId',
      type: 'slot',
      required: true,
      list: 'enableList',
    },
    {
      label: '是否异步',
      value: 'isAsyn',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '是否启用',
      value: 'isEnable',
      type: 'radio-model',
      code: 'yes_or_no',
    },
  ],
  rules: {},
  labelWidth: '100px',
})
const listTypeInfo = ref({
  enableList: [
    {
      key: '是',
      value: 1,
    },
    {
      key: '否',
      value: 0,
    },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: {
    create: '添加',
  },
  visible: false,
  type: '',
  width: '40%',
  btLoading: false,
  btList: [
    { label: '关闭', type: '', icon: '', event: close, show: true },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: save,
      saveLoading: false,
      show: true,
    },
  ],
})
const selectUserInfo = ref({
  visible: false,
  saveEmpty: true,
  api: {
    system: getThirdSystemAll,
    interface: getInvokeInterfaceAll,
  },
  query: {
    type: 'normal',
  },
})
const selectInterfaceType = ref({
  visible: false,
  saveEmpty: true,
})
const canDisabled = computed(() => {
  return (
    tableInfo.value.selections.length &&
    //后台状态值都是数字
    tableInfo.value.selections.filter((row) => row.isEnable !== 0).length === 0
  )
})
const canEnabled = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((row) => row.isEnable !== 1).length === 0
  )
})
function getIds(row) {
  if (row) {
    return [row.id]
  } else {
    return tableInfo.value.selections.map((value) => value.id)
  }
}
function showUpdate(data) {
  formInfo.value.data = { ...data }
  dialogInfo.value.type = 'update'
  dialogInfo.value.visible = true
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 初始化验证
function initRules() {
  formInfo.value.rules = proxy.$initRules(formInfo.value.fieldList)
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 创建
function create() {
  formInfo.value.data = { isAsyn: 0 }
  dialogInfo.value.type = 'create'
  dialogInfo.value.visible = true
}
function enable(row) {
  const ids = getIds(row)
  if (ids.length === 0) {
    proxy.$message({
      message: `请选择`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
  startInvokeSystemConfig(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disable(row) {
  const ids = getIds(row)
  if (ids.length === 0) {
    proxy.$message({
      message: `请选择`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
  stopInvokeSystemConfig(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
// 删除
function del(data) {
  deleteInvokeSystemConfig([data.id]).then((res) => {
    if (res && res.success) {
      tableInfo.value.refresh = Math.random()
    }
  })
}
function close() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let api = createInvokeSystemConfig
      if (dialogInfo.value.type === 'update') {
        api = updateInvokeSystemConfig
      }
      const params = formInfo.value.data
      dialogInfo.value.btLoading = true
      api(params)
        .then((res) => {
          if (res.success) {
            dialogInfo.value.visible = false
            tableInfo.value.refresh = Math.random()
          }
          dialogInfo.value.btLoading = false
        })
        .catch((e) => {
          dialogInfo.value.btLoading = false
        })
    }
  })
}
function openSystemList() {
  selectUserInfo.value.visible = true
}
function openInterfaceTypePage() {
  selectInterfaceType.value.visible = true
}
function selectUserCallBack(row) {
  formInfo.value.data['interfaceId'] = row.id
  formInfo.value.data['interfaceName'] = row.name
}
function selectInterfaceTypeCallBack(row) {
  formInfo.value.data['type'] = row.key
  formInfo.value.data['typeName'] = row.value
}
function getOptionLabel(data, option) {
  const result = _.find(option, ['value', data])
  return result ? result.key : '-'
}
onMounted(() => {
  getList()
  initRules()
})
</script>

<style scoped></style>
